from django.contrib import admin, messages
from django.utils.translation import gettext_lazy, gettext
from django.contrib.admin import helpers
from django.core.exceptions import ValidationError

from utils.crypto.rsa import SHA256WithRSA
from utils.model import NoDeleteSelectModelAdmin, BaseModelAdmin
from apps.app_aai_proxy.models import AAIProxyConfig, AAIUserInfo, SysProxyApp
from apps.app_aai_proxy.managers import aai_proxy_configs


@admin.register(AAIProxyConfig)
class AAIProxyConfigAdmin(NoDeleteSelectModelAdmin):
    list_display = ['id', 'name', 'value', 'creation_time', 'update_time', 'remark']
    list_display_links = ['id', 'name']
    actions = ('update_configs', 'check_jwt_keys')
    show_full_result_count = False

    @admin.action(description=gettext_lazy('清理更新配置项'))
    def update_configs(self, request, queryset):
        aai_proxy_configs.get_configs_no_cache(remove_invalid=True)

    update_configs.act_not_need_selected = True

    @admin.action(description=gettext_lazy('校验JWT密钥对是否匹配'))
    def check_jwt_keys(self, request, queryset):
        aai_proxy_configs.get_configs_no_cache(remove_invalid=False)
        private_key = aai_proxy_configs.get(AAIProxyConfig.ConfigName.JWT_PRIVATE_KEY.value)
        public_key = aai_proxy_configs.get(AAIProxyConfig.ConfigName.JWT_PUBLIC_KEY.value)
        if not private_key:
            self.message_user(request=request, message=gettext('jwt私钥未配置'), level=messages.WARNING)
            return

        if not public_key:
            self.message_user(request=request, message=gettext('jwt公钥未配置'), level=messages.WARNING)
            return

        if SHA256WithRSA.is_key_pair_match(private_key=private_key, public_key=public_key):
            self.message_user(request=request, message=gettext('JWT公钥与私钥校验成功'), level=messages.SUCCESS)
        else:
            self.message_user(request=request, message=gettext('JWT公钥与私钥不匹配'), level=messages.ERROR)

    check_jwt_keys.act_not_need_selected = True

    def changelist_view(self, request, extra_context=None):
        if request.method == "POST":
            action = self.get_actions(request)[request.POST['action']][0]
            act_not_need_selected = getattr(action, 'act_not_need_selected', False)
            if act_not_need_selected:
                post = request.POST.copy()
                post.setlist(helpers.ACTION_CHECKBOX_NAME, [0])
                request.POST = post

        return super().changelist_view(request, extra_context)

    def get_changelist_instance(self, request):
        cl = super().get_changelist_instance(request)
        cl.show_admin_actions = True
        return cl

    def save_model(self, request, obj, form, change):
        super().save_model(request=request, obj=obj, form=form, change=change)
        aai_proxy_configs.clear_cache()


@admin.register(AAIUserInfo)
class AAIUserInfoAdmin(BaseModelAdmin):
    list_display = ['id', 'source_id', 'email', 'true_name', 'type', 'org_name', 'create_time', 'create_user',
                    'update_time', 'update_user']
    list_display_links = ['id', 'email']
    search_fields = ['email', 'source_id', 'org_name']


@admin.register(SysProxyApp)
class SysProxyAppAdmin(BaseModelAdmin):
    list_display = ['id', 'name', 'url', 'state', 'create_time', 'create_user', 'update_time', 'update_user']
    list_display_links = ['id',]
    search_fields = ['name', 'url']
